package com.jz.community.moduleshoppingguide.home.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.jz.community.basecomm.base.BaseMvpLoadFragment;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.loaction.LocActivity;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.ColorUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.view.RelativePopupWindow;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.home.bean.CategoriesBean;
import com.jz.community.moduleshoppingguide.home.bean.ChunnelCategoriesBean;
import com.jz.community.moduleshoppingguide.home.presenter.HomePresenter;
import com.jz.community.moduleshoppingguide.home.ui.HomeView;
import com.jz.community.moduleshoppingguide.home.ui.adapter.HomeAdapter;
import com.jz.community.moduleshoppingguide.home.ui.view.HomeTabPopupWindow;
import com.jz.community.moduleshoppingguide.search.bean.SearchHotKeyWordInfo;
import com.jz.community.moduleshoppingguide.search.task.SearchHotKeyWordTask;
import com.jz.community.moduleshoppingguide.search.ui.SearchActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeFragment extends BaseMvpLoadFragment<HomeView.View, HomePresenter> implements HomeView.View, HomeTabPopupWindow.ICategoriesClick {


    @BindView(R2.id.home_main_address_tv)
    TextView homeMainAddressTv;
    @BindView(R2.id.home_main_address_iv)
    ImageView homeMainAddressIv;
    @BindView(R2.id.home_main_address_ll)
    RelativeLayout homeMainAddressLl;
    @BindView(R2.id.home_main_search_iv)
    ImageView homeMainSearchIv;
    @BindView(R2.id.home_main_search_tv)
    TextView homeMainSearchTv;
    @BindView(R2.id.home_main_search_ll)
    LinearLayout homeMainSearchLl;
    @BindView(R2.id.home_main_message_iv)
    ImageView homeMainMessageIv;
    @BindView(R2.id.home_main_message_point)
    ImageView homeMainMessagePoint;
    @BindView(R2.id.home_main_message_ll)
    LinearLayout homeMainMessageLl;
    @BindView(R2.id.home_main_layout)
    LinearLayout homeMainLayout;
    @BindView(R2.id.home_main_toolbar)
    Toolbar homeMainToolbar;
    @BindView(R2.id.home_main_tab)
    SlidingTabLayout homeMainTab;
    @BindView(R2.id.home_main_tab_switch)
    ImageView homeMainTabSwitch;
    @BindView(R2.id.home_main_vp)
    ViewPager homeMainVp;
    @BindView(R2.id.home_title_layout)
    LinearLayout homeTitleLayout;

    HomeAdapter homeAdapter;
    public static final int REQUEST_CODE_LOCATION = 10246;
    private SearchHotKeyWordInfo.EmbeddedBean searchHotWordInfo;
    HomeTabPopupWindow homeTabPopupWindow;

    private float transparentTwoAlpha = 0.2f;
    private float transparentAlpha = 0f;
    private int alpha_255 = 255;
    private int alpha_102 = 102;
    private Palette.Swatch mVibrant;
    private View homeBanner;
    private int indexPosition;
    private int maxAlpha;
    private int inPos;
    private int mDistance;
    private boolean isScollLoadData;
    private List<Fragment> itemFragmentList;

    private HomeFindFragment homeFindFragment;

    private ShoppingGuidePageFragment shoppingGuidePageFragment;

    private int mViewPagerPosition;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shoppingguide_fragment_home;
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        switchTabStateTransparency(2);
    }

    /**
     * 切换Tab状态透明度
     *
     * @param index
     */
    private void switchTabStateTransparency(int index) {
        switch (index) {
            case 0:
                setActiveToolbarAGB(true);
                setBannerActiveStyle(true);
                setImmersionBar(homeMainToolbar, transparentAlpha);
                break;
            case 1:
                setActiveToolbarAGB(true);
                setBannerActiveStyle(false);
                setImmersionBar(homeMainToolbar, transparentAlpha);
                break;
            case 2:
                setActiveToolbarAGB(false);
                setOtherHomeActiveParams();
                setImmersionBar(homeMainToolbar, transparentTwoAlpha);
                break;
        }
    }

    /**
     * 设置活动透明度ToolBar透明度
     */
    private void setActiveToolbarAGB(boolean isUpdateStyle) {
        homeMainToolbar.setBackgroundColor(Color.argb(maxAlpha, alpha_255, alpha_255, alpha_255));
        if (!Preconditions.isNullOrEmpty(mVibrant) && isUpdateStyle) {
            setHomeBackgroundColor(mVibrant);
            LoggerUtils.fLog().i("RGB " + ColorUtils.toRGBHexString(mVibrant.getRgb()));
        } else {
            if (homeBanner != null) {
                SHelper.gone(homeBanner);
                homeBanner.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
            }
        }
    }

    /**
     * 活动样式
     */
    private void setBannerActiveStyle(boolean isShowColor) {
        setTabBtnIcon(R.mipmap.home_main_message_white, R.mipmap.home_main_tab_type_white);
        homeMainSearchLl.setBackground(getActivity().getResources().getDrawable(R.drawable.tb_search_round_whilte));
        setHomeMainTabColor(isShowColor);
    }

    /**
     * 设置Tab资源
     *
     * @param messTabSources
     * @param messTabTypeSources
     */
    private void setTabBtnIcon(int messTabSources, int messTabTypeSources) {
        homeMainMessageIv.setBackgroundResource(messTabSources);
        homeMainTabSwitch.setBackgroundResource(messTabTypeSources);
    }

    /**
     * 颜色渐变
     *
     * @param isShowColor
     */
    private void setHomeMainTabColor(boolean isShowColor) {
        if (!isShowColor && mDistance > 200) {
            homeMainAddressTv.setTextColor(Color.argb(maxAlpha, alpha_102, alpha_102, alpha_102));
            homeMainTab.setTextUnselectColor(Color.argb(maxAlpha, alpha_102, alpha_102, alpha_102));
            homeMainTab.setTextSelectColor(Color.argb(maxAlpha, alpha_102, alpha_102, alpha_102));
            homeMainTab.setIndicatorColor(Color.argb(maxAlpha, alpha_102, alpha_102, alpha_102));
            setTabBtnIcon(R.mipmap.home_main_message, R.mipmap.home_main_tab_type);
        } else {
            homeMainAddressTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.white));
            homeMainTab.setTextUnselectColor(ContextCompat.getColor(getActivity(), R.color.white));
            homeMainTab.setTextSelectColor(ContextCompat.getColor(getActivity(), R.color.white));
            homeMainTab.setIndicatorColor(ContextCompat.getColor(getActivity(), R.color.white));
        }
    }

    /**
     * 设置当前其他页参数
     */
    private void setOtherHomeActiveParams() {
        homeMainToolbar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
        setTabBtnIcon(R.mipmap.home_main_message, R.mipmap.home_main_tab_type);
        homeMainSearchLl.setBackground(getActivity().getResources().getDrawable(R.drawable.tb_search_round));
        homeMainAddressTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_gary));
        homeMainTab.setTextUnselectColor(ContextCompat.getColor(getActivity(), R.color.font_gary));
        homeMainTab.setTextSelectColor(ContextCompat.getColor(getActivity(), R.color.home_red));
        homeMainTab.setIndicatorColor(ContextCompat.getColor(getActivity(), R.color.home_red));
    }

    @Override
    protected void initVisible() {
        if (inPos == 0) {
            if (isScollLoadData) {
                switchTabStateTransparency(indexPosition);
            } else {
                switchTabStateTransparency(2);
            }
        } else {
            switchTabStateTransparency(2);
        }

        if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
            mPresenter.unreadCount("member");
        }
    }

    @Override
    protected void initDatas() {

        itemFragmentList = new ArrayList<>();

        mBaseLoadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);
        });

        mBaseLoadService.setCallBack(EmptyCallback.class, (context, view) -> {
            ImageView mIvEmpty = view.findViewById(R.id.empty_img);
            mIvEmpty.setImageResource(R.mipmap.empty_default);
            TextView textView = view.findViewById(R.id.empty_tv);
            textView.setText("暂无数据！");
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void clickError() {

    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        getHomeData();
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_MESSAGE_POINT) {
            //邻里圈无数据时点击空view跳转到附近页面
            if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
                mPresenter.unreadCount("member");
            }
        }
    }

    public void refreshData() {
        if (homeFindFragment != null) {
            homeFindFragment.getChunnelHomePageData();
        }
    }

    public void getHomeData() {
        isScollLoadData = false;
        RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(getActivity());
        if (region != null) {
            if (!RxDataTool.isNullString(region.getName())) {
                initLocData(region.getName());
                mPresenter.getChunnelCategories(region.getId());
                getSearchHotKeyWordTask();
            }
        }
        if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
            mPresenter.unreadCount("member");
        }
    }


    @Override
    protected void addListener() {
        homeMainAddressLl.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LocActivity.class);
            getActivity().startActivityForResult(intent, REQUEST_CODE_LOCATION);
        });
        homeMainTabSwitch.setOnClickListener(v -> {
            if (homeTabPopupWindow != null) {
                homeTabPopupWindow.showOnAnchor(homeMainToolbar, RelativePopupWindow.VerticalPosition.BELOW, RelativePopupWindow.HorizontalPosition.ALIGN_LEFT, 0, 0);
            }
        });
    }

    @Override
    public void showChannel(List<ChunnelCategoriesBean> cList) {
        mBaseLoadService.showSuccess();
        List<CategoriesBean> list = new ArrayList<>();

        CategoriesBean categoriesBean = new CategoriesBean();
        categoriesBean.setName("发现");
        list.add(0, categoriesBean);

        if (cList != null && cList.size() > 0) {
            SHelper.vis(homeMainTabSwitch);
            for (int i = 0; i < cList.size(); i++) {
                CategoriesBean c = new CategoriesBean();
                c.setParentCategoryId(cList.get(i).getId());
                c.setCategoriesId(cList.get(i).getId());
                c.setName(cList.get(i).getName());
                list.add(c);
            }
            updateFragmentList(list);
            setPage(list);
        } else {
            updateFragmentList(list);
            setPage(list);
        }
    }

    /**
     * 更新FragmentList
     *
     * @param cList
     */
    private void updateFragmentList(List<CategoriesBean> cList) {
        for (int i = 0; i < cList.size(); i++) {
            if (i == 0) {
                homeFindFragment = HomeFindFragment.newInstance();
                itemFragmentList.add(homeFindFragment);
            } else {
                shoppingGuidePageFragment = ShoppingGuidePageFragment.newInstance(cList.get(i).getCategoriesId());
                itemFragmentList.add(shoppingGuidePageFragment);
            }
        }
    }

    private void setPage(List<CategoriesBean> list) {
        homeAdapter = new HomeAdapter(getFragmentManager(), list, itemFragmentList);
        homeMainVp.setAdapter(homeAdapter);
        homeMainTab.setViewPager(homeMainVp);
        homeMainVp.setOffscreenPageLimit(list.size());
        homeMainTab.setCurrentTab(0);
        homeMainVp.addOnPageChangeListener(onPageChangeListener);
        homeFindFragment.setHomeStyleCallback(new HomeFindFragment.HomeStyleCallback() {
            @Override
            public void updateHomeStyle(int index, int alpha, int distance) {
                updateScollHomeStyle(index, alpha, distance);
            }

            @Override
            public void updateHomeToolbarStyle(Palette.Swatch vibrant, View homeBannerView, boolean isBannerData) {
                updateSwitchHomeStyle(vibrant, homeBannerView, isBannerData);
            }
        });
        homeTabCategoriesUI(list);
    }

    /**
     * 当前Tab滑动位置Position
     */
    public void setViewPagerPosition(int viewPagerPosition) {

        mViewPagerPosition = viewPagerPosition;

        if (mViewPagerPosition == 0) {
            homeFindFragment.setHomeFindBannerAutoPlay(true);
        } else {
            homeFindFragment.setHomeFindBannerAutoPlay(false);
        }
    }

    /**
     * 更新滑动透明度
     *
     * @param index
     * @param alpha
     * @param distance
     */
    private void updateScollHomeStyle(int index, int alpha, int distance) {
        maxAlpha = alpha;
        indexPosition = index;
        mDistance = distance;
        switchTabStateTransparency(index);
    }

    /**
     * 更新切换背景颜色
     *
     * @param vibrant
     * @param homeBannerView
     * @param isLoadData
     */
    private void updateSwitchHomeStyle(Palette.Swatch vibrant, View homeBannerView, boolean isLoadData) {
        isScollLoadData = isLoadData;
        if (isLoadData) {
            mVibrant = vibrant;
            homeBanner = homeBannerView;
            if (inPos == 0 && indexPosition != 2) {
                if (mViewPagerPosition == 0) {
                    setHomeBackgroundColor(vibrant);
                    switchTabStateTransparency(0);
                }
            }
        } else {
            if (mViewPagerPosition == 0) {
                switchTabStateTransparency(2);
            }
        }
    }

    /**
     * 设置首页Banner背景颜色
     *
     * @param vibrant
     */
    private void setHomeBackgroundColor(Palette.Swatch vibrant) {
        if (!Preconditions.isNullOrEmpty(vibrant.getRgb())) {
            try {
                SHelper.vis(homeBanner);
                String rgbColor = ColorUtils.parseStyleColor(ColorUtils.toRGBHexString(vibrant.getRgb()));
                homeTitleLayout.setBackgroundColor(Color.parseColor(rgbColor));
                homeBanner.setBackgroundColor(Color.parseColor(rgbColor));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 首页Tab分类
     *
     * @param list
     */
    private void homeTabCategoriesUI(List<CategoriesBean> list) {
        homeTabPopupWindow = new HomeTabPopupWindow(getActivity(), list);
        homeTabPopupWindow.setiCategoriesClick(this);
        homeTabPopupWindow.setAdapterChoose(0);
    }

    private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            inPos = position;
            homeMainTab.setCurrentTab(position);
            homeTabPopupWindow.setAdapterChoose(position);
            if (position == 0) {
                if (isScollLoadData) {
                    switchTabStateTransparency(indexPosition);
                    SHelper.vis(homeBanner);
                } else {
                    switchTabStateTransparency(2);
                    SHelper.gone(homeBanner);
                }
            } else {
                SHelper.gone(homeBanner);
                switchTabStateTransparency(2);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void initLocData(String city) {
        if (!TextUtils.isEmpty(city)) {
            String city_str = city.substring(city.length() - 1);
            if (city_str.equals("市")) {
                homeMainAddressTv.setText(city.substring(0, (city.length() - 1)));
            } else {
                homeMainAddressTv.setText(city);
            }
        }
    }

    /**
     * 获取热搜词
     */
    private void getSearchHotKeyWordTask() {
        new SearchHotKeyWordTask(getActivity(), o -> {
            SearchHotKeyWordInfo searchHotKeyWordInfo = (SearchHotKeyWordInfo) o;
            if (!Preconditions.isNullOrEmpty(searchHotKeyWordInfo)) {
                loadSearchHotKeyWordInfo(searchHotKeyWordInfo);
            }
        }).execute();
    }

    /**
     * 加载显示热搜词
     *
     * @param searchHotKeyWordInfo
     */
    private void loadSearchHotKeyWordInfo(SearchHotKeyWordInfo searchHotKeyWordInfo) {
        searchHotWordInfo = searchHotKeyWordInfo.get_embedded();
        if (!Preconditions.isNullOrEmpty(searchHotWordInfo)) {
            for (SearchHotKeyWordInfo.EmbeddedBean.ContentBean contentBean : searchHotWordInfo.getContent()) {
                homeMainSearchTv.setText("大家都在搜索:" + contentBean.getHotSearchWord());
                break;
            }
        }
    }

    @OnClick(R2.id.home_main_search_ll)
    public void searchClick() {
        Intent intent = new Intent(getActivity(), SearchActivity.class);
        startActivity(intent);
    }

    @OnClick(R2.id.home_main_message_iv)
    public void messageClick() {
        if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.PUSH_MESSAGE);
        } else {
            BaseUserUtils.showIsLoginDialog(getActivity());
        }
    }

    @Override
    public void showError(String s, int type) {
        if (type == 0) {
            mBaseLoadService.showSuccess();
            homeFindFragment = HomeFindFragment.newInstance();
            itemFragmentList.add(homeFindFragment);
            List<CategoriesBean> list = new ArrayList<>();
            CategoriesBean categoriesBean = new CategoriesBean();
            categoriesBean.setName("发现");
            list.add(0, categoriesBean);
            homeAdapter = new HomeAdapter(getFragmentManager(), list, itemFragmentList);
            if (homeMainVp != null) {
                homeMainVp.setAdapter(homeAdapter);
            }
            homeMainTab.setViewPager(homeMainVp);
        }
    }

    @Override
    public void onItemClick(CategoriesBean categoriesBean, int position) {
        homeMainVp.setCurrentItem(position, true);
    }

    @Override
    public void showCount(Integer count) {
        if (count > 0) {
            homeMainMessagePoint.setVisibility(View.VISIBLE);
        } else {
            homeMainMessagePoint.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
